package com.leesche.zcsp.node.pay.wecha.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import org.apache.log4j.Logger;

import com.leesche.zcsp.node.pay.wecha.data.PayInfo;
import com.leesche.zcsp.node.pay.wecha.service.encha.impl.WechatServiceImpl;
import com.leesche.zcsp.node.utils.PayConfig;

/**
 * 请求校验工具�?
 * 
 * @author liufeng
 * @date 2013-05-18
 */
public class SignUtil {
	private final static Logger logger = Logger.getLogger(SignUtil.class);

	private static String token = "headingtech";

	/**
	 * 验证签名
	 * 
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static boolean checkSignature(String signature, String timestamp, String nonce) {
		String[] arr = new String[] { token, timestamp, nonce };
		// 将token、timestamp、nonce三个参数进行字典序排�?
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;

		try {
			md = MessageDigest.getInstance("SHA-1");
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			byte[] digest = md.digest(content.toString().getBytes());
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		content = null;
		// 将sha1加密后的字符串可与signature对比，标识该请求来源于微�?
		return tmpStr != null && tmpStr.equals(signature.toUpperCase());
	}

	/**
	 * 将字节数组转换为十六进制字符�?
	 * 
	 * @param byteArray
	 * @return
	 */
	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	/**
	 * 将字节转换为十六进制字符�?
	 * 
	 * @param mByte
	 * @return
	 */
	private static String byteToHexStr(byte mByte) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];

		String s = new String(tempArr);
		return s;
	}
	
	/*订单支付详情**/
	public static Map<String,String>  paySign(String pack) {
		 Map<String, String> ret = new HashMap<String, String>();
	        String nonce_str = create_nonce_str();
	        String timestamp = create_timestamp();
	        String string1;
	        String signature = "";

	        string1 = "appId=" + PayConfig.appid +
	                  "&noncestr=" + nonce_str +
	                  "&timestamp=" + timestamp +
	                  "&signType=MD5"  +
	                  "&package=" + pack;
	        System.out.println(string1);

	        try
	        {
	            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
	            crypt.reset();
	            crypt.update(string1.getBytes("UTF-8"));
	            signature = byteToHex(crypt.digest());
	        }
	        catch (NoSuchAlgorithmException e)
	        {
	            e.printStackTrace();
	        }
	        catch (UnsupportedEncodingException e)
	        {
	            e.printStackTrace();
	        }

	        ret.put("appId", PayConfig.appid);
	        ret.put("nonceStr", nonce_str);
	        ret.put("timestamp", timestamp);
	        ret.put("paySign", signature);
	        ret.put("signType", "MD5");
	        ret.put("package", pack);

	        return ret;
		
	}
	
	
	 public static Map<String, String> sign(String jsapi_ticket, String url) {
	        Map<String, String> ret = new HashMap<String, String>();
	        String nonce_str = create_nonce_str();
	        String timestamp = create_timestamp();
	        String string1;
	        String signature = "";

	        //注意这里参数名必须全部小写，且必须有�?
	        string1 = "jsapi_ticket=" + jsapi_ticket +
	                  "&noncestr=" + nonce_str +
	                  "&timestamp=" + timestamp +
	                  "&url=" + url;

	        try
	        {
	            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
	            crypt.reset();
	            crypt.update(string1.getBytes("UTF-8"));
	            signature = byteToHex(crypt.digest());
	        }
	        catch (NoSuchAlgorithmException e)
	        {
				logger.error(e.getMessage(),e);
	        }
	        catch (UnsupportedEncodingException e)
	        {
				logger.error(e.getMessage(),e);
	        }

	        ret.put("url", url);
	        ret.put("jsapi_ticket", jsapi_ticket);
	        ret.put("nonceStr", nonce_str);
	        ret.put("timestamp", timestamp);
	        ret.put("signature", signature);
	        ret.put("appid", PayConfig.appid);

	        return ret;
	    }

	public static Map<String, String> sign2(String jsapi_ticket, String url) {
		Map<String, String> ret = new HashMap<String, String>();
		String nonce_str = create_nonce_str();
		String timestamp = create_timestamp();
		String string1;
		String signature = "";

		//注意这里参数名必须全部小写，且必须有�?
		string1 = "jsapi_ticket=" + jsapi_ticket +
				"&noncestr=" + nonce_str +
				"&timestamp=" + timestamp +
				"&url=" + url;

		try
		{
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		}
		catch (NoSuchAlgorithmException e)
		{
			logger.error(e.getMessage(),e);
		}
		catch (UnsupportedEncodingException e)
		{
			logger.error(e.getMessage(),e);
		}

		ret.put("url", url);
		ret.put("jsapi_ticket", jsapi_ticket);
		ret.put("nonceStr", nonce_str);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);
		ret.put("appid", PayConfig.SINOPAY_APPID_TEST);

		return ret;
	}


	private static String byteToHex(final byte[] hash) {
	        Formatter formatter = new Formatter();
	        for (byte b : hash)
	        {
	            formatter.format("%02x", b);
	        }
	        String result = formatter.toString();
	        formatter.close();
	        return result;
	    }

	    public  static String create_nonce_str() {
	        return UUID.randomUUID().toString();
	    }

	    public  static String create_timestamp() {
	        return Long.toString(System.currentTimeMillis() / 1000);
	    }
	    public static String getRandomStringByLength(int length) {
	        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
	        Random random = new Random();
	        StringBuffer sb = new StringBuffer();
	        for (int i = 0; i < length; i++) {
	            int number = random.nextInt(base.length());
	            sb.append(base.charAt(number));
	        }
	        return sb.toString();
	    }
	    /***
	     * <获取支付签名>
	     * @param payInfo
	     * @return
	     * @throws Exception
	     */
	    public static  String getSign(PayInfo payInfo) throws Exception {
	        String signature = "";
	    	  String signTemp = "appid="+payInfo.getAppid()
	    	   +"&attach="+payInfo.getAttach()
	    	   +"&body="+payInfo.getBody()
	    	   +"&device_info="+payInfo.getDevice_info()
	    	   +"&mch_id="+payInfo.getMch_id()
	    	   +"&nonce_str="+payInfo.getNonce_str()
	    	   +"¬ify_url="+payInfo.getNotify_url()
	    	   +"&openid="+payInfo.getOpenid()
	    	   +"&out_trade_no="+payInfo.getOut_trade_no()
	    	   +"&spbill_create_ip="+payInfo.getSpbill_create_ip()
	    	   +"&total_fee="+payInfo.getTotal_fee()
	    	   +"&trade_type="+payInfo.getTrade_type()
	    	   +"&key="+PayConfig.partnerkey; //这个key注意
	    	  try
		        {
		            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
		            crypt.reset();
		            crypt.update(signTemp.getBytes("UTF-8"));
		            signature = byteToHex(crypt.digest());
		        }
		        catch (NoSuchAlgorithmException e)
		        {
		            e.printStackTrace();
		        }
		        catch (UnsupportedEncodingException e)
		        {
		            e.printStackTrace();
		        }

	    	 return signature;
	    }
	    /***
	     * 
	    * @Title: getOrderNo 
	    * @Description: TODO(获取订单号) 
	    * @param @return   
	    * @return String   
	    * @throws
	     */
		public static String getOrderNo() {
			return UUID.randomUUID().toString().replace("-", "");
		}
	    
	    
}
